#include "widget.h"
#include "ui_widget.h"
#include "onlineuser.h"
#include <QMessageBox>
#include <QShortcut>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("网络聊天室");
    ui->pushButton_send->setEnabled(false);
    this->setLayout(ui->verticalLayout);
    this->setWindowIcon(QIcon(":/chicken.png"));

    //创建QShortcut对象
    QShortcut *shortcut_send = new QShortcut(this);
    shortcut_send->setKey(QKeySequence(Qt::Key_Return));

    connect(shortcut_send,&QShortcut::activated,[=](){
        //触发发送按钮的点击信号
        ui->pushButton_send->clicked();
    });

    //创建套接字
    client = new QTcpSocket(this);

    //为bind按钮绑定信号槽，向服务器发起连接
    connect(ui->pushButton_connect,&QPushButton::clicked,[=](){
        //获取服务器IP和端口
        QString clientIp = ui->lineEdit_ip->text();
        QString clientPort = ui->lineEdit_port->text();

        //向服务器发起连接
        if(!clientIp.isEmpty() && !clientPort.isEmpty()){
            client->connectToHost(clientIp,clientPort.toInt());
        }
    });

    //当连接建立成功的处理
    connect(client,&QTcpSocket::connected,[=](){
        //将connect按钮设为不可用
        ui->pushButton_connect->setEnabled(false);

        //将发送按钮变为可用
        ui->pushButton_send->setEnabled(true);
    });

    //当可读信号触发后
    connect(client,&QTcpSocket::readyRead,[=](){
        //读取服务器发送的消息
        QString msg = client->readAll();

        //如果是获取当前在线人数，我们做特殊处理
        QString str = "GET_ONLINE_COUNT\n"; //与服务端约定的协议·
        if(msg.contains("GET_ONLINE_COUNT\n")){
                //删除报头
                msg.remove(0,str.size());

                //创建一个widget用于显示当前在线用户
                OnlineUser *online = new OnlineUser();
                QListWidget * listWidget = new QListWidget(online);
                listWidget->resize(600,600);
                listWidget->addItem(msg);

                online->setAttribute(Qt::WA_DeleteOnClose);
                online->show();

                return;
        }

        //将消息显示至listWidget上
        ui->listWidget->addItem(msg);
    });

    //当连接断开信号触发后
    connect(client,&QTcpSocket::disconnected,[=](){
        QMessageBox::warning(this,"连接已断开","长时间未活跃，已将你踢出聊天室...");
        this->close();
    });

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_send_clicked()
{
    //获取输入框的消息
    QString context = ui->lineEdit_send_message->text();
    if(context.isEmpty()){
        //如果为空，直接return
        return ;
    }

    //发送消息
    client->write(context.toUtf8());

    //将输入框清空
    ui->lineEdit_send_message->setText("");
}

void Widget::on_pushButton_clicked()
{
    QString context = "GET_ONLINE_COUNT";
    client->write(context.toUtf8());
}
